package com.itheima.filter;

import com.itheima.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "LoginCheckFilter",value = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest hreq = (HttpServletRequest) req;
        HttpServletResponse hresp = (HttpServletResponse) resp;

        String reqURI = hreq.getRequestURI();
        log.info("拦截到请求：{}",reqURI);

        String[] paths = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/page/login/login.html",
                "/**/api/**",
                "/**/api/**",
                "/**/images/**",
                "/**/js/**",
                "/**/plugins/**",
                "/**/styles/**",
                "/**/*.ico",
                "/user/sendMsg",
                "/user/login",
                "/user/logout",
                "/front/page/login.html",
//                "/**/page/**"
        };

        for (String path : paths) {
            if(PATH_MATCHER.match(path,reqURI)){
                chain.doFilter(req, resp);//匹配上了就放行
                return;
            }
        }

        //判断登录状态
        Object employeeId = hreq.getSession().getAttribute("employeeID");
        if(employeeId != null){
            BaseContext.setCurrentId((Long) employeeId);
            chain.doFilter(req, resp);
            return;
        }



        //判断登录状态
        Object userId = hreq.getSession().getAttribute("userId");
        if(userId != null){
            BaseContext.setCurrentId((Long) userId);
            chain.doFilter(req, resp);
            return;
        }


        //未登录就跳转到登录页面
        if(reqURI.contains("/front")){
            hresp.sendRedirect("/front/page/login.html");
        }
        if(reqURI.contains("/backend")){
            hresp.sendRedirect("/backend/page/login/login.html");
        }





    }


}
